<?php
/**
 * Created by PhpStorm.
 * User: Simpson
 * Date: 2016/8/29
 * Time: 17:42
 */

namespace App\Http\Controllers\Repair;

use App\Http\Controllers\Wechat\HomeController;
use App\Model\Repair;
use App\Model\User;
use App\Repository\RepairRepository;
use Illuminate\Http\Request;
use RepairService;
use Carbon\Carbon;
class RepairController extends HomeController
{
    public $repair;

    public function __construct(RepairRepository $repair)
    {
        $this->repair = $repair;
    }

    public function getView()
    {

        return RepairService::getView();

    }

    public function addRepair(Request $request)
    {

        $this->validate($request, [
            'description' => 'required',
            'cellphone' => 'required',
            'ordertime' => 'required',
        ]);

        //判断是否有存在未完成预约
        if(!$this->repair->isUserHaveUnfinishOrder(\Auth::guard('wechat')->user()->open_id))
            return response()->json(['msg' => '只能存在一个未完成预约喔！']);


        //判断该日期是否超过预约数
        if(!$this->repair->isOrderOverload($request->input('ordertime')))
            return response()->json(['msg' => '该预约日期预约已满，请选择其它日期!']);


        $description = $request->input('description');
        $platform = $request->input('platform');
        $orderTime = Carbon::parse($request->input('ordertime'));
        $schedule = $request->input('schedule');
        $cellPhone = $request->input('cellphone');
        $shortPhone = $request->input('shortphone');
        $address = $request->input('address');

        //修改user中的宿舍地址、联系方式，并添加预约信息
        $result = RepairService::addRepair($platform, $description, $orderTime, $schedule, $cellPhone, $shortPhone, $address);

        return $result? response()->json(['msg' => 'ok', 'target' => route('repair')]): response()->json(['msg' => '预约失败']);

    }

    public function cancelRepair(Request $request)
    {
        $id = $request->input('id');
        $result = RepairService::cancelOrder($id);

        return $result? response()->json(['msg' => 'ok', 'target' => route('repair')]): response()->json(['msg' => '关闭失败']);

    }
    

}